import { useEffect, useState, useRef } from 'react'
import './style.less'
import { HsAdminSpin, HsAdminTable, useESPage } from '@hs-admin/base-components'
import Filter from './components/Filter/Filter'
import CardList from './components/cardList/cardList'
import TableSearchBox from './components/industryTableSearchBox/tableSearchBox'
import { Flex, Popover, Table } from 'antd'
import { allProvinceList, allCityList } from '@hs-admin/utils'
import exportImg from './img/export.png'
import added from './img/added.png'
import notAdd from './img/notAdd.png'
import saved from './img/saved.png'
import notSave from './img/notSave.png'
// import { useNewPage } from '@hs-admin/utils'
import { getCompanyRanksList, getCompanyRanksTableList, setFavorite, getFavoriteList, cancelFavorite } from '@/api/company.ts'
import { message } from '@hs-admin/utils'
import { MonitorsList } from '@hs-server/components'
import { addmonitorsitems, has_datas, deletemonitors } from '@/api/home'
import { openCompanyDetail } from 'hs-react-company'
import { useExportCompanyListModal } from 'hs-react-company'

// 处理省级数据
allProvinceList.unshift({
  label: '全国',
  value: '全国'
})

// 处理市级数据
Object.keys(allCityList).forEach((key) => {
  if (allCityList[key].length > 1) {
    allCityList[key].unshift({
      province: '',
      label: '全省',
      value: '全省'
    })
  }
})

const currentDate = new Date()
const currentYear = currentDate.getFullYear()
const yearOptions = [
  {
    label: currentYear,
    value: currentYear
  },
  {
    label: currentYear - 1,
    value: currentYear - 1
  },
  {
    label: currentYear - 2,
    value: currentYear - 2
  },
  {
    label: currentYear - 3,
    value: currentYear - 3
  },
  {
    label: currentYear - 4,
    value: currentYear - 4
  }
]

const CompanyList2 = () => {
  const [loading, setloading] = useState(true)
  const [Tags, setTags] = useState<any>({ label: currentYear - 1, value: currentYear - 1 })
  const [cityTags, setCityTags] = useState<any>({ label: '全省', value: '全省' })
  const [cardList, setCardList] = useState<any>([])
  const [selectedCard, setSelectedCard] = useState<any>()
  const [search, setSearch] = useState<any>({})
  // const [viewQualityList, setViewQualityList] = useState<any>([])
  const [ismonitor, setismonitor] = useState(false)
  const [source_id, setsource_id] = useState('')

  const conitorsListRef: any = useRef({})
  // const [total, setTotal] = useState(23423)
  const addmonitorsitem = (id: any, name: any) => {
    if (!ismonitor) {
      addmonitors_items(id, name)
    } else delemonitors(id)
  }

  const addmonitors_items = (id: any, name: any) => {
    addmonitorsitems({ data_id: source_id, list_id: id, data_name: name }).then((_res: any) => {
      message.success('监测成功')
      getList()
    })
  }
  const delemonitors = (id: any) => {
    deletemonitors({ list_id: id, data_id: source_id }).then((_res: any) => {
      message.success('取消监测成功')
      getList()
    })
  }

  const handleAdd = (data: any) => {
    setsource_id(data.companyCode)
    setismonitor(data.added)
    conitorsListRef.current.showModal(!data.added ? null : data.companyCode)
  }
  const handleSave = (item: any) => {
    if (!item.saved) {
      const params = {
        company_ids: [item.companyId]
      }
      setFavorite(params).then(() => {
        message.success('收藏成功')
        getList()
      })
    } else {
      const params = {
        id: item.companyId
      }
      cancelFavorite(params).then(() => {
        message.success('取消收藏成功')
        getList()
      })
    }
  }
  const handleCardClick = (item: any) => {
    if (item) {
      setSelectedCard(item)
      // getList
    } else {
      setSelectedCard(null)
    }
  }
  // 查看全部资质
  // const getCompanyQuality = (item: any) => {
  //   getQualityList({ companyCode: item.companyCode }).then((res: any) => {
  //     let arr
  //     if (res?.data?.qualifiedList) {
  //       arr = res.data.qualifiedList.map((item: any) => item.name)
  //     }
  //     setViewQualityList(arr)
  //   })
  // }
  const columns: any = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      render: (_: string, _record: any, index: number) => <>{index + 1 + (pagination.current - 1) * pagination.pageSize}</>
    },
    {
      title: '公司名称',
      width: 120,
      dataIndex: 'companyName',
      key: 'name',
      render: (data: any, row: any) => {
        return (
          <span style={{ color: '#0779FF', cursor: 'pointer' }} onClick={() => openCompanyDetail(row.companyCode, 'industryWarning')}>
            {data}
          </span>
        )
      }
    },
    {
      title: '当前榜单',
      width: 100,
      dataIndex: 'rankType'
    },
    {
      title: '公告日期',
      dataIndex: 'noticeDate',
      key: 'noticeDate',
      width: 120
    },
    {
      title: '注册地区',
      dataIndex: 'regAddress',
      key: 'regAddress',
      width: 150,
      render: (data: any, row: any) => {
        let str = ''
        if (row.province) {
          str += `${row.province}`
          if (row.city && row.city !== '重庆市' && row.city !== '北京市' && row.city !== '上海市' && row.city !== '天津市') {
            str += `-${row.city}`
            if (row.area) {
              str += `-${row.area}`
            }
          }
          if ((row.city == '重庆市' || row.city == '北京市' || row.city == '上海市' || row.city == '天津市') && row.area) {
            str += `-${row.area}`
          }
        }
        return <span>{str}</span>
      }
    },
    {
      title: '法人',
      dataIndex: 'legalRep',
      key: 'legalRep',
      width: 80
    },
    {
      title: '企业类型',
      dataIndex: 'companyType',
      key: 'companyType',
      width: 150
    },
    {
      title: '成立时间',
      dataIndex: 'foundDate',
      key: 'foundDate',
      width: 120
    },
    {
      title: '注册资本',
      dataIndex: 'recapitalAmtCal',
      key: 'recapitalAmtCal',
      width: 150,
      render: (data: any) => {
        return data ? `${(data / 10000).toFixed(0)}万元` : '--'
      }
    },
    {
      title: '国标行业分类',
      dataIndex: 'neaInd',
      key: 'neaInd',
      width: 150,
      render: (data: any) => {
        let datas: any = []
        const columns = [
          {
            title: '行业门类',
            width: 120,
            dataIndex: 'type0',
            key: 'type0'
          },
          {
            title: '行业大类',
            width: 120,
            dataIndex: 'type1',
            key: 'type1'
          },
          {
            title: '行业中类',
            width: 120,
            dataIndex: 'type2',
            key: 'type2'
          },
          {
            title: '行业细类',
            width: 120,
            dataIndex: 'type3',
            key: 'type3'
          }
        ]
        const qualityArr = data ? data[0].split('-') : []
        if (data) {
          datas = [
            {
              type0: qualityArr[0] || '--',
              type1: qualityArr[1] || '--',
              type2: qualityArr[2] || '--',
              type3: qualityArr[3] || '--'
            }
          ]
        }
        const content = (
          <div style={{ maxHeight: '400px', overflowY: 'scroll' }}>
            <Table dataSource={datas} columns={columns} pagination={false} />
          </div>
        )
        return data && data.length ? (
          <Popover content={content} trigger="click">
            <span style={{ color: '#0779FF', cursor: 'pointer' }}>{qualityArr[0]}</span>
          </Popover>
        ) : (
          '--'
        )
      }
    },
    {
      title: '火石行业分类',
      dataIndex: 'hsInd',
      key: 'hsInd',
      width: 150,
      render: (data: any) => {
        const datas: any = []
        const columns = [
          {
            title: '一级分类',
            width: 120,
            dataIndex: 'type0',
            key: 'type0'
          },
          {
            title: '二级分类',
            width: 120,
            dataIndex: 'type1',
            key: 'type1'
          },
          {
            title: '三级分类',
            width: 120,
            dataIndex: 'type2',
            key: 'type2'
          },
          {
            title: '四级分类',
            width: 120,
            dataIndex: 'type3',
            key: 'type3'
          }
        ]
        const newData = data ? data.sort() : []
        newData.forEach((element: any) => {
          const arr = element.split('-')
          datas.push({
            type0: arr[0] || '--',
            type1: arr[1] || '--',
            type2: arr[2] || '--',
            type3: arr[3] || '--'
          })
        })
        const content = (
          <div style={{ maxHeight: '400px', overflowY: 'scroll' }}>
            <Table dataSource={datas} columns={columns} pagination={false} />
          </div>
        )
        return data && data.length ? (
          <Popover content={content} trigger="click">
            <span style={{ color: '#0779FF', cursor: 'pointer' }}>
              {datas.length > 1 ? `${datas[0].type0}等${datas.length}个领域` : `${datas[0].type0}`}
            </span>
          </Popover>
        ) : (
          '--'
        )
        // const arr: any = []
        // data?.forEach((element: string, index: number) => {
        //   if (index < data?.length - 1) {
        //     arr.push(<span style={{ color: '#0779FF', cursor: 'pointer' }}>{element}、</span>)
        //   } else {
        //     arr.push(<span style={{ color: '#0779FF', cursor: 'pointer' }}>{element}</span>)
        //   }
        // })
        // return arr && arr.length ? arr : '--'
      }
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 100,
      render: (row: any) => {
        return (
          <div style={{ display: 'flex', cursor: 'pointer' }}>
            {row.saved ? (
              <div onClick={() => handleSave(row)}>
                <Popover content={'取消收藏'} trigger="hover">
                  <img style={{ width: '20px', height: '20px', marginRight: '17px' }} src={saved} alt="" />
                </Popover>
              </div>
            ) : (
              <div onClick={() => handleSave(row)}>
                <Popover content={'收藏'} trigger="hover">
                  <img style={{ width: '20px', height: '20px', marginRight: '17px' }} src={notSave} alt="" />
                </Popover>
              </div>
            )}
            {row.added ? (
              <div onClick={() => handleAdd(row)}>
                <img style={{ width: '20px', height: '20px' }} src={added} alt="" />
              </div>
            ) : (
              <div onClick={() => handleAdd(row)}>
                <img style={{ width: '20px', height: '20px' }} src={notAdd} alt="" />
              </div>
            )}
          </div>
        )
      }
    }
  ]

  const [data, setdata] = useState([])
  // 筛选改变后请求数据
  const handleSetSearch = (data: any) => {
    if (data && JSON.stringify(data) !== '{}') {
      setSearch(data)
    } else {
      setSearch({})
    }
    // getList()
  }
  const getList = async () => {
    // const arr: any = []
    // await setTimeout(() => {
    //   for (let i = 0; i < 10; i++) {
    //     arr.push({
    //       key: i,
    //       companyName: `xxx公司`,
    //       saved: i % 2 ? true : false,
    //       added: i % 2 ? true : false,
    //       nowQualification: 32,
    //       publicDate: `2021.5`,
    //       publicCompany: `xxxxx企业`,
    //       allQualification: `3`,
    //       registArea: '杭州市',
    //       legalPerson: 'xxx',
    //       companyType: `高新技术企业`,
    //       fundTime: `2019.5`,
    //       regitCapital: `5000万元`,
    //       standardClassification: `独角兽企业`,
    //       hsClassification: `创新型企业`
    //     })
    //   }
    //   setdata(arr)
    // }, 1000)
    const params: any = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      // provinceCode: Tags.label === '全国' ? undefined : Tags.value,
      // cityCode: cityTags.label === '全省' ? undefined : cityTags.value,
      year: Tags.label,
      rankType: selectedCard ? selectedCard.rank_type : undefined,
      ...search
    }
    if (params.publishDate && !params.publishDate[0] && !params.publishDate[1]) {
      params.publishDate = undefined
    }
    setrequestParams(params)
    const result = await getCompanyRanksTableList(params)
    const params1 = {
      page: 1,
      page_size: 999
    }
    const favoriteResult = await getFavoriteList(params1)
    favoriteResult?.items?.forEach((element: any) => {
      result?.data?.list.forEach((ele: any) => {
        if (element.id === ele.companyId) {
          ele.saved = true
        }
      })
    })
    // 检查监测列表
    const companyIdArr: any = []
    result?.data?.list.forEach((item: any) => {
      companyIdArr.push(item.companyCode)
    })
    const monitorResult = await has_datas({ data_ids: companyIdArr })
    result?.data?.list.forEach((ele: any) => {
      ele.added = monitorResult[ele.companyCode]
    })
    settotalNumber(result?.data?.total)
    setdata(result?.data?.list)
    return {
      current: result?.data?.pageNum,
      pageSize: result?.data?.pageSize,
      total: result?.data?.total,
      list: result?.data?.list
    }
  }
  // const { pagination, resetPage } = useNewPage(getList)
  const [totalNumber, settotalNumber] = useState(0)
  const { ESPage, pagination, resetPage } = useESPage({ total: totalNumber, showTotal: false, initPageSize: 10 })
  // 导出
  const [requestParams, setrequestParams] = useState({})
  const { ExportModal, showModal } = useExportCompanyListModal({ requestParams, dataTotal: totalNumber })
  const getCardList = () => {
    const params = {
      page: 1,
      page_size: 999,
      expand: 'aggs',
      enabled: true,
      year: Tags.label
    }
    getCompanyRanksList(params).then((res: any) => {
      setCardList(
        res.items.map((i: any) => {
          return {
            ...i,
            label: i.rank_type,
            value: i.companies_count,
            tag: i.rank_level
          }
        })
      )
      setSelectedCard(null)
    })
  }
  useEffect(() => {
    let ignore = false
    if (pagination.current != 1) {
      resetPage()
    } else {
      if (!ignore) {
        getList()
      }
    }

    return () => {
      ignore = true
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [search, selectedCard, cityTags])
  useEffect(() => {
    let ignore = false
    if (!ignore) {
      getList()
    }
    return () => {
      ignore = true
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pagination])
  useEffect(() => {
    setCityTags(allCityList[Tags.value] ? allCityList[Tags.value][0] : { label: '全省', value: '全省' })
  }, [Tags])

  useEffect(() => {
    getCardList()

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [cityTags])

  useEffect(() => {
    setloading(false)
  }, [])
  return (
    <div className="company-list1-page-wrapper">
      {loading && <HsAdminSpin />}
      <Flex gap="large" vertical>
        <h1 className="module-title">重点企业榜单</h1>
        <div className="filter-wrap">
          <Filter key="provinceFilter" selectedTags={[Tags]} setSelectedTags={setTags} tagsData={yearOptions} label="年份选择" />
        </div>
        {cardList?.length ? (
          <div>
            <CardList cardListData={cardList} handleClick={handleCardClick}></CardList>
          </div>
        ) : null}
        <div className="tableWrapBox">
          <TableSearchBox setSearchValue={handleSetSearch} searchValue={search}></TableSearchBox>
          <div style={{ marginTop: '18px', marginBottom: '8px' }}>
            <Flex gap="large" justify="space-between" align="center">
              <div className="totalText">共 {totalNumber} 家</div>
              <Flex align="center">
                <img style={{ width: '16px', height: '16px', marginRight: '8px' }} src={exportImg} alt="" />
                <span className="export" onClick={showModal}>
                  导出excel
                </span>
              </Flex>
            </Flex>
          </div>
          <HsAdminTable
            id="qualityTable"
            columns={columns}
            dataSource={data}
            scroll={{ x: false, y: false }}
            pagination={false}
            rowKey="id"
            size="small"
          />
          <Flex justify="flex-end">{ESPage}</Flex>
        </div>
      </Flex>
      <MonitorsList ref={conitorsListRef} addmonitorsitem={addmonitorsitem} />
      {ExportModal}
    </div>
  )
}

export default CompanyList2
